package com.situ.springboot.controller;

import com.situ.springboot.util.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    //MultipartFile file 封装了前端传递过来的图片信息
    @RequestMapping("/uploadImage")
    @ResponseBody
    public Result uploadImage(MultipartFile file) {
        //e710da3725db4f3d8fd796a329aabfa0
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 1.jpg
        String filename = file.getOriginalFilename();
        // png
        String extension = FilenameUtils.getExtension(filename);
        // e710da3725db4f3d8fd796a329aabfa0.png
        String newFilename = uuid + "." + extension;
        String filePath = "D:\\mypic\\" + newFilename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //把新的图片的名字返回给前台
        return Result.ok("上传成功", newFilename);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        //4cfae34e-8123-4150-8b2d-916ec4a65bd9
        System.out.println(uuid);
        //e710da3725db4f3d8fd796a329aabfa0
        System.out.println(uuid.replace("-", ""));
    }
}
